package com.qfedu.buy.server.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.SAXWriter;
import org.dom4j.io.XMLWriter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: NeighborBuy
 * @description:
 * @author: Feri(邢朋辉)
 * @create: 2021-02-01 09:26
 */
public class XmlUtil {
    /**
     * 生成xml
     * <xml>
     *    <appid>wx2421b1c4370ec43b</appid>
     *    <attach>支付测试</attach>
     *    <body>JSAPI支付测试</body>
     *    <mch_id>10000100</mch_id>
     * </xml>   */
    public static String createXml(Map<String,String> map){
        //创建文档对象
        Document document= DocumentHelper.createDocument();
        //创建根节点
        Element root=document.addElement("xml");
        //遍历Map集合  循环生成子节点
        for(String s:map.keySet()){
            //创建子节点
            Element child=root.addElement(s);
            child.setText(map.get(s));
        }
        //将生成的xml写出到内存中
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        try {
            //实例化xml输出对象
            XMLWriter writer=new XMLWriter(baos);
            //将文档写出到内存流
            writer.write(document);
            writer.close();
            //将xml格式转换为字符串
            return new String(baos.toByteArray());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 解析xml*/
    public static Map<String,String> parseXml(String xmlStr){
        //实例化读取对象
        SAXReader reader=new SAXReader();
        try {
            Map<String,String> map=new HashMap<>();
            //实例化文档对象
            Document document=reader.read(new ByteArrayInputStream(xmlStr.getBytes()));
            //获取根节点
            Element root=document.getRootElement();
            //遍历根节点下面的所有子节点
            List<Element> childs=root.elements();
            for(Element e:childs){
                map.put(e.getName(),e.getTextTrim());
            }
            return map;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }
}
